package com.think.archive.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.think.archive.annotation.AdminPassToken;
import com.think.archive.annotation.CheckSecretKey;
import com.think.archive.annotation.PassToken;
import com.think.archive.annotation.UserLoginToken;
import com.think.archive.mapper.SysUserMapper;
import com.think.archive.model.SysUser;
import com.think.archive.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;

public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    SysUserMapper userMapper;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        String secret = httpServletRequest.getHeader("secret");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }else if (method.isAnnotationPresent(AdminPassToken.class)) {
            AdminPassToken adminPassToken = method.getAnnotation(AdminPassToken.class);
            if (adminPassToken.required()&&"admin".equals(secret)) {
                return true;
            }
        }
        else if(method.isAnnotationPresent(CheckSecretKey.class)||method.isAnnotationPresent(UserLoginToken.class)){
            //登录认证
            if(token==null&&httpServletRequest.getParameterMap().containsKey("appKey")){
                CheckSecretKey checkSecretKey = method.getAnnotation(CheckSecretKey.class);
                if (checkSecretKey.required()) {
                    String appKey=httpServletRequest.getParameter("appKey");
                    String sign=httpServletRequest.getParameter("sign");
                    if(StringUtils.isEmpty(appKey)){
                        throw new RuntimeException("请输入appKey");
                    }
                    if(StringUtils.isEmpty(sign)){
                        throw new RuntimeException("请重新输入sign");
                    }
                    SecretKey secretKey= (SecretKey) redisUtil.get(appKey);
                    if(secretKey.getRequestSecretEndTime()>=new Date().getTime()/1000&&sign.toLowerCase().equals(DigestUtils.md5DigestAsHex((appKey+secretKey.getRequestSecret()).getBytes()).toLowerCase())){
                        return true;
                    }else{
                        throw new RuntimeException("秘钥已失效");
                    }
                }
            }else if (token!=null&&!httpServletRequest.getParameterMap().containsKey("appKey")){
                UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
                if (userLoginToken.required()) {
                    String userId;
                    try {
                        userId = JWT.decode(token).getAudience().get(0);
                    } catch (JWTDecodeException j) {
                        throw new RuntimeException("401");
                    }
                    SysUser user = userMapper.selectByPrimaryKey(Integer.valueOf(userId));
                    if (user == null) {
                        throw new RuntimeException("用户不存在，请重新登录");
                    }
                    JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getUsername())).build();
                    try {
                        jwtVerifier.verify(token);
                    } catch (JWTVerificationException e) {
                        throw new RuntimeException("401");
                    }
                    return true;
                }
            }
        }
        throw new RuntimeException("401");
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
